package com.tqyan.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
//@RefreshScope
public class ExcelUtils {

    /**
     * 导出固定格式的Excel文件,固定格式如下：
     * 1.表头样式-居中对齐；
     * 2.内容样式-靠左对齐;
     * 3.Excel类型为XLSX
     */
    public static String  writeExcelWithFixCellStyle(List<?> datas, Class<?> clazz, String fileName) throws Exception {
        @Cleanup ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置内容靠左对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        EasyExcel.write(outputStream, clazz).excelType(ExcelTypeEnum.XLSX).autoCloseStream(true)
                .sheet(clazz.getSimpleName()).registerWriteHandler(horizontalCellStyleStrategy).doWrite(datas);
        byte[] content = outputStream.toByteArray();
        @Cleanup InputStream ipStream = new ByteArrayInputStream(content);
        return fileName+"-"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
    }

}


